package controllers

import (
	"beegoProject10/models/auth"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

type HomeController struct {
	beego.Controller
}

func (c *HomeController) Get() {

	// 1. 初始化数据库
	o := orm.NewOrm()
	qs := o.QueryTable("sys_auth")

	// 2. 初始化数据
	auths := []auth.Auth{}

	// 3. 查询
	qs.Filter("pid", 0).All(&auths)

	// 13. 初始化一个切片
	trees := []auth.Tree{}

	// 4. 递归过滤多级菜单
	for _, authData := range auths {

		pid := authData.Id // 根据pid获取所有子节点
		// 5. 初始化
		treeData := auth.Tree{
			Id:       authData.Id,
			AuthName: authData.AuthName,
			UrlFor:   authData.UrlFor,
			Weight:   authData.Weight,
			Children: []*auth.Tree{},
		}
		// 7. 调用 GetChildNode
		GetChildNode(pid, &treeData)

		// 14. 追加写入数据
		trees = append(trees, treeData)
	}

	fmt.Println("trees: ⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️")
	fmt.Println(trees)

	// 循环三级菜单
	for _, t1 := range trees {
		fmt.Println("一级菜单: ", t1)
		for _, t2 := range t1.Children {
			fmt.Println("二级菜单: ", t2)
		}
	}
	fmt.Println("trees: ⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️")

	c.Data["trees"] = trees
	c.TplName = "index.html"
}

func (c *HomeController) Welcome() {
	c.TplName = "welcome.html"
}

// GetChildNode  6. 定义GetChildNode
func GetChildNode(pid int, treeNode *auth.Tree) {

	// 8.查询出全部的二级菜单，存入auths内
	o := orm.NewOrm()
	qs := o.QueryTable("sys_auth")
	auths := []auth.Auth{}
	_, err := qs.Filter("pid", pid).All(&auths)
	if err != nil {
		return
	}

	// 9. 循环auths继续查询三级及以上的菜单
	for i := 0; i < len(auths); i++ {
		pids := auths[i].Id // 根据pid获取所有子节点

		// 10. 初始化
		treeData := auth.Tree{
			Id:       auths[i].Id,
			AuthName: auths[i].AuthName,
			UrlFor:   auths[i].UrlFor,
			Weight:   auths[i].Weight,
			Children: []*auth.Tree{},
		}

		// 12. 追加写入Children
		treeNode.Children = append(treeNode.Children, &treeData)

		// 11. 调用 GetChildNode
		GetChildNode(pids, &treeData)
	}

	return
}
